package com.zhouk.cws.controller;

import com.zhouk.cws.domain.User;
import com.zhouk.cws.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * Create By Zhouke on 2019/02/25
 */
@Controller
public class LoginController {
    private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login() {
        return "/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("username", username);
        session.setMaxInactiveInterval(30 * 60);
        LOG.info("[{}] login at {}", username, new Date());
        return "redirect:/";
    }

    @PostMapping("/ajax_login")
    @ResponseBody
    public User ajaxLogin(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request){

        User user = userService.findUser(username);
        if(user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            session.setMaxInactiveInterval(30 * 60);
            LOG.info("[{}] login at {}", username, new Date());
            return user;
        } else {
            return null;
        }
    }

    @GetMapping("logout")
    public String logout(HttpServletRequest request){
        request.getSession().invalidate();
        return "redirect:/";
    }
}
